import  createError from 'http-errors';
import  express from 'express';
import cors from 'cors'
import  path from 'path';
import  cookieParser from 'cookie-parser';
import  logger from 'morgan';
import  indexRouter from './routes/index.js';

import  usersRouter from './routes/users.js';
import loginRouter from './api/login.js';
import handleUserAccount from './api/handleUserAccount.js';
import handleUserInformation from './api/handleUserInformation.js';
import handleUserTaskInformation from './api/handleUserTaskInformation.js';
import configurationManage from './api/configurationManage.js'

import {logRecord} from './api/middleWare/index.js'

import handleAiChat from './api/handleAIChat.js'

import handleAppFile from './api/handleAppVersion.js'

import { fileURLToPath } from 'url';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);



var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use(cors())

// 添加日志记录  ---
app.use(logRecord)
app.use('/', indexRouter);
app.use('/', loginRouter);
app.use('/', handleUserAccount);

app.use('/', handleAppFile); // checkLogin

// 下面的带路由校验或者角色权限校验
// 路由文件里边带全局权限校验（全局角色校验）的要放在不带权限校验的文件后面——待完善
app.use('/', configurationManage);  //checkLogin
app.use('/', handleUserInformation);  //checkLogin



app.use('/', handleAiChat); // checkLogin  //checkUserRole
app.use('/', handleUserTaskInformation); // checkLogin  //checkUserRole



app.use('/users', usersRouter);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

export default app;
